﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using HugeFlow.CommandPattern;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Browser;
using System.Xml.Linq;

namespace HugeFlow
{
    public class ImageSearchPanelViewModel : ViewModelBase
    {
        #region Properties

        private readonly string APIKEY = "238bbefb0ef459884c7fbc17ff11b349";
        private readonly string SECRET = "6137adb7e28a5c38";

        #region Items

        private ObservableCollection<FlickrPhoto> _items;
        /// <summary>
        /// 검색된 아이템
        /// </summary>
        public ObservableCollection<FlickrPhoto> Items
        {
            get
            {
                return _items;
            }
            set
            {
                _items = value;

                OnPropertyChanged("Items");
            }
        }

        #endregion Items

        #endregion Properties


        #region Commands


        /// <summary>
        /// SearchImage InstantCommand for ViewModel
        /// </summary>
        private InstantCommand<object> _SearchImageCommand;
        public InstantCommand<object> SearchImageCommand
        {
            get
            {
                return _SearchImageCommand;
            }
            set
            {
                _SearchImageCommand = value;
                OnPropertyChanged("SearchImageCommand");
            }
        }

        private void SearchImageCommandExecute(object parameter)
        {
            // code here
            SearchImage((string)parameter);
        }

        private void SearchImage(string keyword)
        {
            if (string.IsNullOrEmpty(keyword) == true)
            {
                Items = null;
            }

            string requestUrl = string.Format("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key={0}&text={1}&extras=owner_name",
                APIKEY,
                HttpUtility.UrlEncode(keyword));

            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += (object sender, DownloadStringCompletedEventArgs e) =>
                {
                    try // 예외처리 귀찮아서 try-catch합니다. 세미나 용이니 봐주세요.
                    {
                        XDocument xDoc = XDocument.Parse(e.Result);

                        var query = from c in xDoc.Descendants("photo")
                                    select new FlickrPhoto()
                                    {
                                        FarmID = c.Attribute("farm").Value,
                                        ID = c.Attribute("id").Value,
                                        Secret = c.Attribute("secret").Value,
                                        ServerID = c.Attribute("server").Value,
                                        Title = c.Attribute("title").Value,
                                        OwnerName = c.Attribute("ownername").Value
                                    };

                        Items = new ObservableCollection<FlickrPhoto>();
                        foreach (FlickrPhoto item in query)
                        {
                            Items.Add(item);
                        }
                    }
                    catch
                    {
                    }
                };
            wc.DownloadStringAsync(new Uri(requestUrl, UriKind.Absolute));
        }


        /// <summary>
        /// SearchImage InstantCommand for ViewModel
        /// </summary>
        private InstantCommand<object> _getRecentImageCommand;
        public InstantCommand<object> GetRecentImageCommand
        {
            get
            {
                return _getRecentImageCommand;
            }
            set
            {
                _getRecentImageCommand = value;
                OnPropertyChanged("GetRecentImageCommand");
            }
        }

        private void GetRecentImageCommandExecute(object parameter)
        {
            // code here
            string requestUrl = "http://api.flickr.com/services/rest/?method=flickr.photos.getRecent&api_key={0}&extras=owner_name";

            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += (object sender, DownloadStringCompletedEventArgs e) =>
            {
                try // 예외처리 귀찮아서 try-catch합니다. 세미나 용이니 봐주세요.
                {
                    XDocument xDoc = XDocument.Parse(e.Result);

                    var query = from c in xDoc.Descendants("photo")
                                select new FlickrPhoto()
                                {
                                    FarmID = c.Attribute("farm").Value,
                                    ID = c.Attribute("id").Value,
                                    Secret = c.Attribute("secret").Value,
                                    ServerID = c.Attribute("server").Value,
                                    Title = c.Attribute("title").Value,
                                    OwnerName = c.Attribute("ownername").Value
                                };

                    Items = new ObservableCollection<FlickrPhoto>();
                    foreach (FlickrPhoto item in query)
                    {
                        Items.Add(item);
                    }
                }
                catch
                {
                }
            };
            wc.DownloadStringAsync(new Uri(requestUrl, UriKind.Absolute));
        }
        #endregion Commands

        public ImageSearchPanelViewModel()
        {
            SearchImageCommand = new InstantCommand<object>(SearchImageCommandExecute);
            GetRecentImageCommand = new InstantCommand<object>(GetRecentImageCommandExecute);
        }

    }
}
